<template>
  <div class="create">
    <div class="container">
      <div class="publish">
        <h2>发表新攻略</h2>
        <p class="publish_info">分享你的个人游记，让更多人看到哦！</p>
        <el-form ref="form" :model="form">
          <el-form-item>
            <el-input v-model="form.title"></el-input>
          </el-form-item>
          <!-- 富文本框 -->
          <el-form-item>
            <client-only>
              <vue-editor v-model="form.content" :editorToolbar="customToolbar"></vue-editor>
            </client-only>
          </el-form-item>
          <el-form-item label="输入并选择城市">
            <el-autocomplete
              class="inline-input"
              v-model="form.city"
              :fetch-suggestions="querySearch"
              placeholder="请搜索游玩城市"
              :trigger-on-focus="false"
              @select="handleSelect"
            ></el-autocomplete>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="handleSubmit" size="small">发布</el-button>
        <span style="margin: 0 5px 0 15px">或者</span>
        <span class="draftSave" @click="draftSave">保存到草稿</span>
      </div>
      <!-- 草稿箱 -->
      <div class="aside">
        <div class="draftBox">
          <h4>
            草稿箱
            <span class="total">({{$store.state.post.draftLocallist.length}})</span>
            <span class="alldel" @click="delAll">一键清空</span>
          </h4>
          <div class="draft_list">
            <div
              class="draft_item"
              v-for="(item,index) in $store.state.post.draftLocallist"
              :key="index"
            >
              <div class="draft_post_title">{{item.title}}</div>
              <div class="draft_post_foot">
                <p class="create_time">{{item.ctime}}</p>
                <div class="draft_tool">
                  <i class="el-icon-edit draft_edit" @click="draftEdit(index)"></i>
                  <i class="el-icon-delete draft_delete" @click="draftDel(index)"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
//日期转换
import moment from 'moment'
export default {
  data() {
    return {
      form: {
        title: '',
        content: '',
        city: ''
      },
      // 修改富文本框工具栏
      customToolbar: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ header: 1 }],
        [{ header: 2 }],
        [{ list: 'ordered' }, { list: 'bullet' }],
        ['image']
      ],
      //草稿箱数据--弃
      // draftList: [],
      ctime: '',
    }
  },
  methods: {
    //封装动态获取 输入建议城市
    getSuggestCity(value, cb) {
      // 1.根据用户的输入查询输入建议
      // JiPiao - 实时机票城市：http:127.0.0.1:1337/airs/city
      this.$axios({
        url: '/airs/city',
        params: { name: value }
      })
        .then(res => {
          // console.log(res);
          // let list = res.data.data
          // console.log(list);
          //改造数据， querySearch 只能识别键名 为value的值
          let list;
          list = res.data.data.map(v => {
            return { value: v.name }
          })
          if (list.length == 0) {
            cb([{ value: '没有查询到相应的城市' }])
            return
          }
          //用户仅输入一个字，默认添加首个
          // this.form.city = list[0].value
          // console.log(list);
          cb(list);
        })
    },
    //   选择城市
    //   fetch-suggestions 是一个返回输入建议的方法属性，如 querySearch(queryString, cb)
    querySearch(value, cb) {  //获取输入建议   value是当前输入的值,键名必须为value
      this.getSuggestCity(value, cb)
      // console.log(value);
      // cb([
      //   { value: '1' },
      //   { value: '2' },
      //   { value: '3' },
      // ]);
    },
    handleSelect(item) {
      // console.log(item)  //Object
      this.form.city = item.value
    },

    //发布文章
    handleSubmit() {
      this.$store.commit('user/setBackurl', location.href)  //未登录回跳
      //添加表单验证
      let rules = {
        Rtitle: {
          value: this.form.title,
          message: "请填写标题",
        },
        Rcontent: {
          value: this.form.content,
          message: "内容不能为空",
        },
        Rcity: {
          value: this.form.city,
          message: "请输入城市",
        }
      }
      let flag = true;
      //遍历验证规则
      Object.keys(rules).forEach((v) => {
        let item = rules[v];
        // 判断是否输入的内容
        if (!item.value) {
          // 当前数据没有内容
          flag = false;
          this.$confirm(item.message, "提示", {
            confirmButtonText: "确定",
            showCancelButton: false,
            type: "warning",
          });
          return;
        }
      });
      if (!flag) {
        return;
      }

      // 发布文章请求
      this.$axios({
        method: 'post',
        url: '/posts',
        headers: { Authorization: 'Bearer ' + this.$store.state.user.userinfo.token },
        data: this.form
      })
        .then(res => {
          console.log(res);
          this.$message.success(res.data.message)
          this.form = {
            title: '',
            content: '',
            city: ''
          }
        })
        .catch(err => {
          console.dir(err)
        })
    },
    //存到草稿
    draftSave() {
      //添加表单验证
      if (this.form.title.trim() == '') {
        this.$confirm('请输入标题', "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning",
        });
        return;
      }
      // this.draftList.push(this.form)
      // console.log(this.draftList);
      this.ctime = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
      // this.ctime = moment(Date.now()).format('YYYY-MM-DD')
      //改造对象
      let draftData = this.form
      draftData.ctime = this.ctime
      // this.draftList = this.draftList.map(item =>
      //   Object.assign(item, { ctime: this.ctime })
      // )
      // console.log(this.draftList)
      // 将草稿数据保存到本地 仓库中 ,
      // this.$store.commit('post/saveDraftPost', this.draftList)
      this.$store.commit('post/saveDraftPost', this.form)
      this.form = {
        title: '',
        content: '',
        city: ''
      }
      this.$message.success('保存成功')
    },
    //删除草稿
    draftDel(index) {
      this.$store.commit('post/delDraftPost', index)  //传入的数据为 选中的索引
    },
    // 编辑草稿
    draftEdit(index) {
      //获取本地仓库的数据--赋值给表单
      this.form = {
        ...this.$store.state.post.draftLocallist[index]
      }
      delete this.form.ctime;
      console.log(this.form);
    },
    delAll() {
      this.$store.commit('post/delAllDraft', [])
    }
  },
}
</script>

<style lang="less" scoped>
.container {
  width: 1000px;
  height: 800px;
  margin: 0 auto;
  padding: 20px 0;
  display: flex;
  justify-content: space-between;
  .publish {
    flex: 3;
    h2 {
      font-weight: 400;
      font-size: 22px;
      margin-bottom: 10px;
    }
    .publish_info {
      font-size: 12px;
      color: #999;
      margin-bottom: 10px;
    }
    /deep/ .ql-editor {
      min-height: 300px;
    }
    .draftSave {
      color: #ffa500;
      &:hover {
        text-decoration: underline;
        cursor: pointer;
      }
    }
  }
  .aside {
    flex: 1;
    padding-left: 20px;
    .draftBox {
      border: 1px solid #ddd;
      padding: 10px;
      h4 {
        margin-bottom: 10px;
        font-weight: 400;
        color: #666;
        .alldel {
          font-size: 12px;
          float: right;
          margin-top: 5px;
          &:hover {
            color: red;
            cursor: pointer;
          }
        }
      }
      .draft_list {
        .draft_item {
          border-bottom: 1px dashed #ddd;
          padding: 10px 0;
          .draft_post_title {
            word-break: break-all;
            text-overflow: ellipsis;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            cursor: pointer;
            margin-bottom: 10px;
            font-size: 15px;
            &:hover {
              color: #ffa500;
              text-decoration: underline;
            }
          }
          .draft_post_foot {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            .create_time {
              color: #999;
            }
            .draft_tool {
              font-size: 16px;
              cursor: pointer;
              .draft_edit {
                margin-right: 5px;
                &:hover {
                  color: #5cd9ef;
                }
              }
              .draft_delete:hover {
                color: #ffa500;
              }
            }
          }
        }
      }
    }
  }
}
</style>